﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using System.Collections.Generic;
using System.Net;
using System.IO;
using ClienteMVC.Dominio;
using System.Text;
using System.Messaging;
using System;

namespace ClienteMVC.Controllers
{
    public class CitaController : Controller
    {
        public ActionResult Create()
        {
            List<SelectListItem> items;

            //REST - Veterinario////////////////////////////////////////////////////////////////////////////
            List<Veterinario> vet = Veterinario_Get();
            items = new List<SelectListItem>();
            foreach (Veterinario i in vet)
                items.Add(new SelectListItem { Text = string.Format("{0} {1}", i.txtVeterinarioNombre.ToString(), i.txtVeterinarioApellidoP.ToString()), Value = i.IdVeterinario.ToString() });
            ViewData["listaveterinario"] = items;

            //REST - Producto////////////////////////////////////////////////////////////////////////////
            List<Producto> prod = Producto_Get();
            items = new List<SelectListItem>();
            foreach (Producto i in prod)
                items.Add(new SelectListItem { Text = i.txtProducto.ToString(), Value = i.IdProducto.ToString() });
            ViewData["listaproducto"] = items;

            //ESTADO CITA////////////////////////////////////////////////////////////////////////////
            ViewData["listaEstados"] = EstadoCita_Get(1);

            //HORAS CITA////////////////////////////////////////////////////////////////////////////
            ViewData["listahoras"] = HorasCita_Get(8);

            //REST - Clientes////////////////////////////////////////////////////////////////////////////
            List<Cliente> Cli = Cliente_Get();
            string FirstValuecli = string.Empty;
            items = new List<SelectListItem>();

            foreach (Cliente i in Cli)
            {
                if (string.IsNullOrEmpty(FirstValuecli))
                {
                    FirstValuecli = i.idCliente.ToString();
                    items.Add(new SelectListItem { Text = i.txtClienteNombre.ToString() + " " + i.txtClienteApellido.ToString(), Value = i.idCliente.ToString(), Selected = true });
                }
                else
                    items.Add(new SelectListItem { Text = i.txtClienteNombre.ToString() + " " + i.txtClienteApellido.ToString(), Value = i.idCliente.ToString() });
            }
            ViewData["listaCliente"] = items;

            //REST - Paciente ////////////////////////////////////////////////////////////////////////////
            List<Paciente> Pac = Paciente_GetbyIdCliente(FirstValuecli);

            items = new List<SelectListItem>();
            foreach (Paciente i in Pac)
                items.Add(new SelectListItem { Text = i.txtPaciente.ToString(), Value = i.IdPaciente.ToString() });

            ViewData["listaPaciente"] = items;

            Cita cita = new Cita();
            cita.FechaCita = DateTime.Now;
            cita.FechaRegistro = DateTime.Now;

            return View(cita);

        }

        [HttpPost]
        public ActionResult Create(FormCollection collection)
        {
            try
            {
                string fecha = collection["FechaCita"] + " " + Request.Form["listahoras"];
                fecha = DateTime.Parse(fecha).ToString("yyyy-MM-dd HH:mm:ss");
                Cita c = null;
                try
                {
                    c = new Cita
                    {
                        FechaCita = DateTime.Parse(fecha),
                        EstadoCita = new EstadoCita { IdEstado = int.Parse(Request.Form["listaEstados"].ToString()), txtEstado = "" },
                        Producto = Producto_GetbyId(Request.Form["listaproducto"].ToString()),
                        Veterinario = Veterinario_GetbyId(Request.Form["listaveterinario"].ToString()),
                        Paciente = Paciente_GetbyId(Request.Form["listaCliente"].ToString(), Request.Form["listaPaciente"].ToString())
                    };
                    Cita_Set(c, 1);

                    return RedirectToAction("Index");
                }
                catch (WebException wex)
                {
                    if (wex.Response != null)
                    {
                        using (var errorResponse = (HttpWebResponse)wex.Response)
                        {
                            using (var reader = new StreamReader(errorResponse.GetResponseStream()))
                            {
                                MensajeRetornoWS error = JSONDeserialize<MensajeRetornoWS>(reader.ReadToEnd());
                                //string error = reader.ReadToEnd();
                                ModelState.AddModelError("", error.txtMensaje);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                string fecha = collection["FechaCita"] + " " + Request.Form["listahoras"];
                fecha = DateTime.Parse(fecha).ToString("yyyy-MM-dd HH:mm:ss");
                Cita c = null;

                c = new Cita
                {
                    FechaCita = DateTime.Parse(fecha),
                    EstadoCita = new EstadoCita { IdEstado = int.Parse(Request.Form["listaEstados"].ToString()), txtEstado = "" },
                    Producto = Producto_GetbyId(Request.Form["listaproducto"].ToString()),
                    Veterinario = Veterinario_GetbyId(Request.Form["listaveterinario"].ToString()),
                    Paciente = Paciente_GetbyId(Request.Form["listaCliente"].ToString(), Request.Form["listaPaciente"].ToString())
                };
                var fltCita = new Func<Cita, object>(o => new { c.IdCita, c.FechaCita, o.EstadoCita, c.Producto, c.Veterinario, c.Paciente, c.Diagnositco });

                string serialized = JSONSerialize(c, fltCita);

                string rutacola = @".\private$\psilva";
                if (!MessageQueue.Exists(rutacola))
                    MessageQueue.Create(rutacola);
                MessageQueue cola = new MessageQueue(rutacola);
                Message mensaje = new Message();
                mensaje.Label = "reservaCita";
                mensaje.Body = new Cita { IdCita = c.IdCita, FechaCita = c.FechaCita,EstadoCita=c.EstadoCita,Producto=c.Producto,Veterinario=c.Veterinario,Paciente=c.Paciente,Diagnositco=c.Diagnositco };
                cola.Send(mensaje);

            }
            return Create();
        }
       

        #region Metodos Genericos
        public string JSONSerialize<T>(T obj, Func<T, object> filter)
        {
            //var fltCita = new Func<Cita, object>(o => new { c.FechaCita, o.IdEstadoCita,c.IdProducto,c.IdVeterinario});
            //string S = Serialize([objectType], fltCita);
            return new JavaScriptSerializer().Serialize(filter(obj));
        }

        public T JSONDeserialize<T>(string input)
        {
            //Cita D = Deserialize<Cita>(S);
            return new JavaScriptSerializer().Deserialize<T>(input);
        }

        public List<SelectListItem> EstadoCita_Get(int idEstado)
        {
            List<SelectListItem> i = new List<SelectListItem>();
            i.Add(new SelectListItem { Text = "Solicitado", Value = "1", Selected = ((idEstado == 1) ? true : false) });
            //i.Add(new SelectListItem { Text = "Confirmado", Value = "2", Selected = ((idEstado == 2) ? true : false) });
            //i.Add(new SelectListItem { Text = "Rechazado", Value = "3", Selected = ((idEstado == 3) ? true : false) });
            //i.Add(new SelectListItem { Text = "Cerrado", Value = "4", Selected = ((idEstado == 4) ? true : false) });
            return i;
        }

        public List<SelectListItem> HorasCita_Get(int Hora)
        {
            List<SelectListItem> i = new List<SelectListItem>();
            int indx = 8;
            while (indx < 19)
            {
                string strHora = string.Format(String.Format("{0:HH}", "01/01/2013 " + indx + ":00"));
                strHora = strHora.Substring(10);
                i.Add(new SelectListItem { Text = strHora, Value = strHora, Selected = ((Hora == indx) ? true : false) });
                indx += 1;
            }
            return i;
        }

        #endregion

        #region Invocacion WS
        //CITA

        private void Cita_Set(Cita c, int accion)
        {
            try
            {
                var fltCita = new Func<Cita, object>(o => new { c.IdCita, c.FechaCita, o.EstadoCita, c.Producto, c.Veterinario, c.Paciente, c.Diagnositco });

                string serialized = JSONSerialize(c, fltCita);

                byte[] data = Encoding.UTF8.GetBytes(serialized);

                ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                //CREAR
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://localhost:23000/CitaService.svc/Citas");
                if (accion == 1)
                    req.Method = "POST";
                else
                    req.Method = "PUT";

                req.ContentLength = data.Length;
                req.ContentType = "application/json";

                var reqStream = req.GetRequestStream();
                reqStream.Write(data, 0, data.Length);

                var res = (HttpWebResponse)req.GetResponse();
                StreamReader reader = new StreamReader(res.GetResponseStream());
                string objJSON = reader.ReadToEnd();
                JavaScriptSerializer js = new JavaScriptSerializer();
                Cita obj = js.Deserialize<Cita>(objJSON);
            }
            catch (WebException wex)
            {
                throw wex;
            }
        }

        private void Cita_Delete(string Id)
        {
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://localhost:23000/CitaService.svc/Citas/" + Id);
            req.Method = "DELETE";
            HttpWebResponse res = (HttpWebResponse)req.GetResponse();
            StreamReader reader = new StreamReader(res.GetResponseStream());

        }

        private Cita Cita_GetbyId(string Id)
        {
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://localhost:23000/CitaService.svc/Citas/" + Id);
            req.Method = "GET";
            HttpWebResponse res = (HttpWebResponse)req.GetResponse();
            StreamReader reader = new StreamReader(res.GetResponseStream());
            return JSONDeserialize<Cita>(reader.ReadToEnd());
        }

        private List<Veterinario> Veterinario_Get()
        {
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://localhost:23000/VeterinarioService.svc/Veterinarios");
            req.Method = "GET";
            HttpWebResponse res = (HttpWebResponse)req.GetResponse();
            StreamReader reader = new StreamReader(res.GetResponseStream());
            return JSONDeserialize<List<Veterinario>>(reader.ReadToEnd());
        }
        private Veterinario Veterinario_GetbyId(string Id)
        {
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://localhost:23000/VeterinarioService.svc/Veterinarios/" + Id);
            req.Method = "GET";
            HttpWebResponse res = (HttpWebResponse)req.GetResponse();
            StreamReader reader = new StreamReader(res.GetResponseStream());
            return JSONDeserialize<Veterinario>(reader.ReadToEnd());
        }

        private List<Producto> Producto_Get()
        {
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://localhost:23000/ProductoService.svc/Productos");
            req.Method = "GET";
            HttpWebResponse res = (HttpWebResponse)req.GetResponse();
            StreamReader reader = new StreamReader(res.GetResponseStream());
            return JSONDeserialize<List<Producto>>(reader.ReadToEnd());
        }
        private Producto Producto_GetbyId(string Id)
        {
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://localhost:23000/ProductoService.svc/Productos/" + Id);
            req.Method = "GET";
            HttpWebResponse res = (HttpWebResponse)req.GetResponse();
            StreamReader reader = new StreamReader(res.GetResponseStream());
            return JSONDeserialize<Producto>(reader.ReadToEnd());
        }

        private List<Cliente> Cliente_Get()
        {
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://localhost:23000/ClienteService.svc/Clientes");
            req.Method = "GET";
            HttpWebResponse res = (HttpWebResponse)req.GetResponse();
            StreamReader reader = new StreamReader(res.GetResponseStream());
            return JSONDeserialize<List<Cliente>>(reader.ReadToEnd());
        }
        private Cliente Cliente_GetbyId(string Id)
        {
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://localhost:23000/ClienteService.svc/Clientes/" + Id);
            req.Method = "GET";
            HttpWebResponse res = (HttpWebResponse)req.GetResponse();
            StreamReader reader = new StreamReader(res.GetResponseStream());
            return JSONDeserialize<Cliente>(reader.ReadToEnd());
        }

        private List<Paciente> Paciente_GetbyIdCliente(string IdCliente)
        {
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://localhost:23000/PacienteService.svc/Pacientes/" + IdCliente);
            req.Method = "GET";
            HttpWebResponse res = (HttpWebResponse)req.GetResponse();
            StreamReader reader = new StreamReader(res.GetResponseStream());
            return JSONDeserialize<List<Paciente>>(reader.ReadToEnd());
        }
        private Paciente Paciente_GetbyId(string IdCliente, string IdPaciente)
        {
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://localhost:23000/PacienteService.svc/Pacientes/" + IdCliente + "/" + IdPaciente);
            req.Method = "GET";
            HttpWebResponse res = (HttpWebResponse)req.GetResponse();
            StreamReader reader = new StreamReader(res.GetResponseStream());
            return JSONDeserialize<Paciente>(reader.ReadToEnd());
        }

        #endregion

    }
}
